import json
import re

def extract_cookies_from_curl(curl_text):
    """从curl命令中提取Cookie"""
    # 查找-b参数后的Cookie字符串，更精确地处理PowerShell转义
    matches = re.findall(r'-b\s+\^"([^"]+)"', curl_text)
    if matches:
        cookie_strs = []
        for match in matches:
            # 替换PowerShell转义字符
            cookie_str = match.replace('^%', '%')
            cookie_strs.append(cookie_str)
        return cookie_strs
    return []

def merge_cookies(cookie_strs):
    """合并多个Cookie字符串"""
    all_cookies = {}
    
    for cookie_str in cookie_strs:
        # 分割各个Cookie
        parts = cookie_str.split('; ')
        for part in parts:
            if '=' in part:
                key, value = part.split('=', 1)
                all_cookies[key] = value
    
    # 重新组合Cookie字符串
    return '; '.join([f"{k}={v}" for k, v in all_cookies.items()])

def main():
    # 读取文件内容
    with open('第一次发布文章请求.txt', 'r', encoding='utf-8') as f:
        first_request = f.read()
    
    with open('第二次发布文章请求.txt', 'r', encoding='utf-8') as f:
        second_request = f.read()
    
    # 从curl命令中提取Cookie
    first_cookie_strs = extract_cookies_from_curl(first_request)
    
    # 合并Cookie
    merged_first = merge_cookies(first_cookie_strs)
    
    # 手动修复URL编码问题
    # 先处理PowerShell特有的转义
    merged_first = merged_first.replace('%^', '%')
    
    # 然后处理标准URL编码
    merged_first = merged_first.replace('%7C', '|')
    merged_first = merged_first.replace('%20', ' ')
    merged_first = merged_first.replace('%3D', '=')
    
    # 读取当前config.json
    with open('config.json', 'r', encoding='utf-8') as f:
        config = json.load(f)
    
    # 更新Cookie字符串
    config['cookie_string'] = merged_first
    
    # 保存更新后的配置
    with open('config_fixed.json', 'w', encoding='utf-8') as f:
        json.dump(config, f, indent=2, ensure_ascii=False)
    
    print("已创建修复后的配置文件: config_fixed.json")
    print("\n修复后的Cookie字符串:")
    print(merged_first)
    
    # 分析Cookie中的关键信息
    print("\nWordPress登录Cookie分析:")
    if 'wordpress_logged_in_6cab87fc114ab2806b437cb159875b8b' in merged_first:
        logged_in_cookie = None
        for part in merged_first.split('; '):
            if part.startswith('wordpress_logged_in_6cab87fc114ab2806b437cb159875b8b='):
                logged_in_cookie = part.split('=', 1)[1]
                break
        
        if logged_in_cookie:
            parts = logged_in_cookie.split('|')
            if len(parts) >= 4:
                username, expiry, token, hash_val = parts[:4]
                print(f"  用户名: {username}")
                print(f"  过期时间戳: {expiry}")
                try:
                    import datetime
                    expiry_date = datetime.datetime.fromtimestamp(int(expiry))
                    print(f"  过期日期: {expiry_date}")
                    now = datetime.datetime.now()
                    remaining = expiry_date - now
                    print(f"  剩余时间: {remaining}")
                except:
                    print(f"  过期日期: 无法解析")
                print(f"  令牌: {token}")
                print(f"  哈希: {hash_val[:20]}...")
    
    # 检查安全Cookie
    if 'wordpress_sec_6cab87fc114ab2806b437cb159875b8b' in merged_first:
        sec_cookie = None
        for part in merged_first.split('; '):
            if part.startswith('wordpress_sec_6cab87fc114ab2806b437cb159875b8b='):
                sec_cookie = part.split('=', 1)[1]
                break
        
        if sec_cookie:
            parts = sec_cookie.split('|')
            if len(parts) >= 4:
                username, expiry, token, hash_val = parts[:4]
                print(f"\nwordpress_sec Cookie:")
                print(f"  用户名: {username}")
                print(f"  过期时间戳: {expiry}")
                try:
                    import datetime
                    expiry_date = datetime.datetime.fromtimestamp(int(expiry))
                    print(f"  过期日期: {expiry_date}")
                except:
                    print(f"  过期日期: 无法解析")
                print(f"  令牌: {token}")
                print(f"  哈希: {hash_val[:20]}...")

if __name__ == "__main__":
    main()